import type { Chain } from '@tarojs/taro'
import Taro from '@tarojs/taro'

import { isExternalUrl } from './validate'

type Config = Omit<Taro.request.Option, 'url' | 'method'>

const BASE_URL = '/'

function interceptor(chain: Chain) {
  const { method, url, data } = chain.requestParams

  if (!isExternalUrl(url)) {
    chain.requestParams.url = BASE_URL + url
  }

  console.log(`http ${method} --> ${url} data: `, data)

  return chain
    .proceed(chain.requestParams)
    .then(res => {
      return res
    })
    .catch(res => {
      console.error(res)
    })
}

function get(
  url: string,
  data?: Record<string, any>,
  config = {} as Config
): Promise<Taro.request.SuccessCallbackResult> {
  return new Promise((resolve, reject) => {
    Taro.request({
      url,
      method: 'GET',
      data,
      ...config,
      success: res => {
        resolve(res)
      },
      fail: res => {
        reject(res)
      }
    })
  })
}

function post(
  url: string,
  data?: Record<string, any>,
  config = {} as Config
): Promise<Taro.request.SuccessCallbackResult> {
  return new Promise((resolve, reject) => {
    Taro.request({
      url,
      method: 'POST',
      data,
      ...config,
      success: res => {
        resolve(res)
      },
      fail: res => {
        reject(res)
      }
    })
  })
}

Taro.addInterceptor(interceptor)

export default {
  get,
  post
}
